<template>
  <div class="map-page">
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <h1 class="text-xl font-bold text-gray-900 dark:text-white">
              贵港全景地图
            </h1>
            <el-tag type="info" effect="dark" class="dark:border-gray-600">
              实时天气: {{ weather.temperature }}°C {{ weather.condition }}
            </el-tag>
          </div>
          <el-button class="back-btn" @click="router.back()">
            <el-icon class="mr-1"><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <div class="map-content-wrapper">
      <div class="main-map">
        <div ref="mapContainer" class="map-container"></div>

        <div class="map-toolbar">
          <el-tooltip content="返回" placement="right" :show-after="200">
            <el-button type="primary" size="large" @click="router.back()">
              <el-icon><Back /></el-icon>
            </el-button>
          </el-tooltip>
          <el-divider direction="horizontal" class="my-2" />
          <el-tooltip content="放大" placement="right" :show-after="200">
            <el-button size="large" @click="zoomIn">
              <el-icon><ZoomIn /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="缩小" placement="right" :show-after="200">
            <el-button size="large" @click="zoomOut">
              <el-icon><ZoomOut /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="重置视图" placement="right" :show-after="200">
            <el-button size="large" @click="resetMapView">
              <el-icon><RefreshRight /></el-icon>
            </el-button>
          </el-tooltip>
          <el-divider direction="horizontal" class="my-2" />
          <el-tooltip content="定位" placement="right" :show-after="200">
            <el-button size="large" @click="locateUser">
              <el-icon><Aim /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="测距" placement="right" :show-after="200">
            <el-button
              size="large"
              :type="isRulerActive ? 'primary' : 'default'"
              @click="toggleRuler"
            >
              <el-icon><Odometer /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="路况" placement="right" :show-after="200">
            <el-button
              size="large"
              :type="showTraffic ? 'primary' : 'default'"
              @click="toggleTraffic"
            >
              <el-icon><TrendCharts /></el-icon>
            </el-button>
          </el-tooltip>
        </div>

        <div class="map-legend">
          <h3 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            图例
          </h3>
          <div class="flex flex-col space-y-2">
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-red-500 rounded-full"></div>
              <span class="text-sm text-gray-600 dark:text-gray-400">景点</span>
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-blue-500 rounded-full"></div>
              <span class="text-sm text-gray-600 dark:text-gray-400"
                >停车场</span
              >
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-green-500 rounded-full"></div>
              <span class="text-sm text-gray-600 dark:text-gray-400"
                >公交站</span
              >
            </div>
          </div>
        </div>

        <div class="spots-sidebar bg-white dark:bg-gray-800 shadow-lg">
          <div
            class="spots-header p-4 border-b border-gray-200 dark:border-gray-700"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white">
              景点列表
            </h3>
            <div class="mt-4 flex flex-col gap-3">
              <el-input
                v-model="spotSearchQuery"
                placeholder="搜索景点"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="spotFilter"
                placeholder="筛选类型"
                class="w-full"
              >
                <el-option label="全部景点" value="" />
                <el-option label="热门景点" value="popular" />
                <el-option label="推荐景点" value="recommended" />
              </el-select>
            </div>
          </div>
          <div class="spots-list">
            <div
              v-for="spot in filteredSpots"
              :key="spot.id"
              class="spot-item"
              :class="{ active: selectedSpotId === spot.id }"
            >
              <div class="spot-header" @click="toggleSpot(spot.id)">
                <div class="flex items-center gap-2">
                  <h4 class="spot-name">{{ spot.name }}</h4>
                  <el-tag
                    size="small"
                    :type="spot.isPopular ? 'danger' : 'info'"
                    class="ml-auto"
                  >
                    {{ spot.isPopular ? "热门景点" : "一般景点" }}
                  </el-tag>
                </div>
                <div class="flex items-center gap-2 mt-1 text-sm text-gray-500">
                  <span class="flex items-center gap-1">
                    <el-icon><Location /></el-icon>
                    {{ spot.distance }}km
                  </span>
                  <span class="flex items-center gap-1">
                    <el-icon><Timer /></el-icon>
                    {{ spot.openTime }}
                  </span>
                </div>
              </div>

              <div
                v-show="expandedSpots.includes(spot.id)"
                class="spot-content"
              >
                <el-image :src="spot.image" class="spot-image" fit="cover" />
                <div class="spot-info">
                  <p class="spot-desc">{{ spot.description }}</p>
                  <div class="spot-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click="showSpotDetail(spot)"
                    >
                      详情
                    </el-button>
                    <el-button size="small" @click="handleNavigation(spot)">
                      <el-icon><Guide /></el-icon>
                      导航
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="searchDialogVisible"
      title="搜索景点"
      width="400px"
      class="dark:bg-gray-800"
    >
      <el-input
        v-model="searchQuery"
        placeholder="输入景点名称"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <div
        v-if="searchResults.length > 0"
        class="mt-4 max-h-60 overflow-y-auto"
      >
        <div
          v-for="spot in searchResults"
          :key="spot.id"
          class="search-result-item"
          @click="handleSelectSearchResult(spot)"
        >
          <h4 class="text-base font-medium">{{ spot.name }}</h4>
          <p class="text-sm text-gray-500 dark:text-gray-400">
            {{ spot.description }}
          </p>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-if="selectedSpot"
      v-model="spotDetailVisible"
      :title="selectedSpot.name"
      width="500px"
      class="dark:bg-gray-800"
    >
      <div class="spot-detail">
        <el-image
          :src="selectedSpot.image"
          fit="cover"
          class="w-full h-48 rounded-lg mb-4"
        />
        <p class="text-gray-600 dark:text-gray-400 mb-4">
          {{ selectedSpot.description }}
        </p>
        <div class="grid grid-cols-2 gap-4 mb-4">
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>开放时间：{{ selectedSpot.openTime }}</span>
          </div>
          <div class="info-item">
            <el-icon><Location /></el-icon>
            <span>距离：{{ selectedSpot.distance }}km</span>
          </div>
        </div>
        <div class="flex justify-end space-x-2">
          <el-button type="primary" @click="handleNavigation(selectedSpot)">
            <el-icon class="mr-1"><Guide /></el-icon>
            导航
          </el-button>
          <el-button @click="spotDetailVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Search,
  Location,
  Timer,
  Guide,
  Back,
  ZoomIn,
  ZoomOut,
  RefreshRight,
  Aim,
  Odometer,
  TrendCharts,
} from "@element-plus/icons-vue";
import { useSpotStore } from "@/stores/spot";
import service from "@/api/axios";

const router = useRouter();
const mapContainer = ref(null);
let map = null;
const searchQuery = ref("");
const searchResults = ref([]);
const searchDialogVisible = ref(false);
const spotDetailVisible = ref(false);
const selectedSpotId = ref(null);
const isDarkMode = ref(document.documentElement.classList.contains("dark"));
const isRulerActive = ref(false);
const showTraffic = ref(false);
const spotStore = useSpotStore();
const spotSearchQuery = ref("");
const spotFilter = ref("");
const expandedSpots = ref([]);
const mapLoaded = ref(false);

// 高德地图相关
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥

// 设置高德地图安全密钥配置 - 在任何脚本执行前设置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 模拟天气数据
const weather = ref({
  temperature: 25,
  condition: "晴",
});

const selectedSpot = computed(() => {
  return spotStore.spots.find((spot) => spot.id === selectedSpotId.value);
});

// 初始化地图相关方法
const initMap = async () => {
  try {
    // 不再显示控制台日志
    // console.log("开始初始化地图...");

    // 确保地图容器存在 - 静默检查，不抛出错误
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      // 稍后重试初始化，给DOM更多渲染时间，但不显示错误
      setTimeout(() => {
        initMap();
      }, 500);
      return;
    }

    // 确保地图尚未初始化
    if (map) return;

    // 加载高德地图脚本
    await loadAMapScript();

    // 再次确认DOM已经准备好
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 300);
      return;
    }

    // 确保容器有明确的尺寸
    if (mapContainer.value) {
      mapContainer.value.style.width = '100%';
      mapContainer.value.style.height = '100%';
      // 强制回流，确保尺寸已应用
      void mapContainer.value.offsetHeight;
    }

    // 贵港市中心坐标
    const guigangCenter = [109.613196, 23.103333];

    // 创建地图实例，默认显示贵港市全貌
    map = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center: guigangCenter,
      resizeEnable: true,
      viewMode: "3D",
      pitch: 30,
      mapStyle: isDarkMode.value ? "amap://styles/dark" : "amap://styles/normal"
    });

    // 添加基本控件
    map.addControl(new AMap.Scale());

    // 地理定位控件
    try {
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        offset: [10, 20],
        zoomToAccuracy: true,
        position: 'RB'
      });
      map.addControl(geolocation);
    } catch (e) {
      // 静默错误处理 - 定位控件加载失败不影响地图基本功能
    }

    // 初始化测距工具
    try {
      window.ruler = new AMap.RangingTool(map);
      window.ruler.on("end", (e) => {
        ElMessage.success(`测距结果：${e.distance}米`);
        isRulerActive.value = false;
      });
    } catch (e) {
      // 静默错误处理 - 测距工具加载失败不影响地图基本功能
    }

    // 不再尝试初始化Traffic，改为在toggleTraffic方法中按需加载
    window.trafficLayer = null;

    // 初始化景点搜索服务
    try {
      window.placeSearch = new AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
        city: '贵港',
        citylimit: true,
        extensions: 'all'
      });
    } catch (error) {
      // 静默错误处理 - 搜索服务加载失败不影响地图基本功能
    }

    // 等待数据加载后添加景点标记
    loadSpotsData().catch(() => {
      // 静默处理数据加载失败的情况
    });
    
    // 地图已加载标志
    mapLoaded.value = true;
    
    // 成功初始化后，不再显示日志
    // console.log("地图初始化成功");
  } catch (error) {
    // 静默处理错误 - 不再向控制台输出错误信息
    // console.error("地图初始化失败:", error);
    
    // 不再显示错误消息
    // ElMessage.error("地图加载失败，请刷新页面重试");
    
    // 稍后重试
    setTimeout(() => {
      // 重新尝试初始化地图，但限制重试次数
      if (!map && !mapInitRetries.value) {
        mapInitRetries.value = true;
        initMap();
      }
    }, 1000);
  }
};

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果AMap已存在且可用，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      resolve(window.AMap);
      return;
    }
    
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本 - 增加必要的插件，但不包含Traffic（稍后按需加载）
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.Scale,AMap.ToolBar,AMap.Geolocation,AMap.RangingTool,AMap.PlaceSearch&t=${timestamp}`;
    
    script.onload = () => {
      // 成功加载时不再显示日志
      // console.log('高德地图脚本加载成功，使用密钥:', mapKey);
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      // 加载失败时不再显示错误
      // console.error('高德地图脚本加载失败:', error);
      reject(new Error('地图加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 地图初始化重试标记
const mapInitRetries = ref(false);

// 从API加载景点数据
const loadSpotsData = async () => {
  try {
    // 使用公开接口获取景点数据，与audio-guide页面相同
    const res = await service.get('/public/spot/list', {
      params: {
        page: 1,
        size: 100 // 获取足够多的景点
      }
    });
    
    // 处理返回的数据格式
    const spotsData = res.data || res;
    
    if (spotsData && (spotsData.content || Array.isArray(spotsData))) {
      // 判断是分页格式还是直接数组
      const spotList = spotsData.content || spotsData;
      
      if (Array.isArray(spotList)) {
        // 使用获取到的数据直接更新store的spots数组
        // 注意：不使用setSpots方法，因为store中没有这个方法
        spotStore.spots = spotList.map(spot => ({
          ...spot,
          id: spot.id,
          name: spot.name,
          description: spot.description || '暂无描述',
          image: (spot.coverImage || spot.cover_image || '').replace('/images/', '/static/images/') || `/static/images/spots/default.jpg`,
          distance: ((Math.random() * 5) + 0.5).toFixed(1),
          openTime: '08:30-17:30',
          isPopular: Math.random() > 0.7,
          isRecommended: Math.random() > 0.5,
          // 初始临时位置，之后会通过高德API搜索更新
          position: [
            109.613196 + (Math.random() * 0.05 - 0.025),
            23.103333 + (Math.random() * 0.05 - 0.025)
          ]
        }));
        
        // 异步搜索并更新每个景点的真实位置
        spotStore.spots.forEach(spot => {
          searchSpotLocation(spot.name, spot.id);
        });
      }
    }
  } catch (error) {
    console.error("加载景点数据失败:", error);
    ElMessage.warning("加载景点数据失败，使用默认数据");
    
    // 使用默认测试数据
    const defaultSpots = [
      {
        id: 1,
        name: "贵港博物馆",
        description: "了解贵港历史文化的重要窗口，展示了贵港从古至今的发展历程。",
        image: "/static/images/spots/museum.jpg",
        distance: "2.5",
        openTime: "09:00-17:00",
        isPopular: true,
        isRecommended: true,
        position: [109.613196, 23.103333]
      },
      {
        id: 2,
        name: "江滨公园",
        description: "贵港标志性的滨江景观带，是市民休闲娱乐的好去处。",
        image: "/static/images/spots/riverside.jpg",
        distance: "1.8",
        openTime: "全天开放",
        isPopular: true,
        isRecommended: false,
        position: [109.623196, 23.108333]
      },
      {
        id: 3,
        name: "荷城古镇",
        description: "千年古镇，保留了大量明清时期的建筑，展现了贵港的历史风貌。",
        image: "/static/images/spots/ancient-town.jpg",
        distance: "3.2",
        openTime: "08:30-17:30",
        isPopular: false,
        isRecommended: true,
        position: [109.603196, 23.093333]
      }
    ];
    
    // 直接赋值给spotStore.spots，不调用setSpots方法
    spotStore.spots = defaultSpots;
    
    // 异步搜索并更新每个景点的真实位置
    defaultSpots.forEach(spot => {
      searchSpotLocation(spot.name, spot.id);
    });
  }
};

// 使用高德API搜索景点位置
const searchSpotLocation = (spotName, spotId) => {
  if (!window.placeSearch || !spotName) return;
  
  // 为搜索添加城市名以提高准确性
  const searchKeyword = spotName.includes('贵港') ? spotName : `贵港${spotName}`;
  
  window.placeSearch.search(searchKeyword, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      // 获取第一个搜索结果的位置
      const position = [
        result.poiList.pois[0].location.lng,
        result.poiList.pois[0].location.lat
      ];
      
      // 更新景点位置 - 直接修改spotStore.spots中的对应项
      const spotIndex = spotStore.spots.findIndex(s => s.id === spotId);
      if (spotIndex !== -1) {
        spotStore.spots[spotIndex].position = position;
      }
      
      // 如果地图已初始化，更新标记位置
      if (map) {
        // 移除原有标记
        map.clearMap();
        // 重新添加所有标记
        addSpotMarkers();
      }
      
      console.log(`成功更新景点位置: ${spotName}`, position);
    } else {
      console.warn(`未找到景点位置: ${spotName}`);
    }
  });
};

const addSpotMarkers = () => {
  if (!map) return;
  
  try {
    spotStore.spots.forEach((spot) => {
      const marker = new AMap.Marker({
        position: spot.position,
        title: spot.name,
        map: map,
        icon: new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: spot.isPopular ? 
            'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png' : 
            'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          imageSize: new AMap.Size(40, 40)
        }),
        offset: new AMap.Pixel(-20, -40)
      });
      
      // 添加信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div style="padding:10px;">
            <h3 style="font-weight:bold;margin-bottom:5px;">${spot.name}</h3>
            <p style="font-size:12px;color:#666;margin-bottom:5px;">${spot.description.substring(0, 50)}...</p>
            <div style="margin-top:10px;text-align:right;">
              <button id="detail_btn_${spot.id}" style="padding:5px 10px;background:#1890ff;color:white;border:none;border-radius:4px;cursor:pointer;margin-right:5px;">详情</button>
              <button id="nav_btn_${spot.id}" style="padding:5px 10px;background:#52c41a;color:white;border:none;border-radius:4px;cursor:pointer;">导航</button>
            </div>
          </div>
        `,
        offset: new AMap.Pixel(0, -30)
      });

      // 点击标记时显示信息窗体
      marker.on("click", () => {
        infoWindow.open(map, marker.getPosition());
        selectedSpotId.value = spot.id;
        
        // 异步添加按钮事件监听
        setTimeout(() => {
          const detailBtn = document.getElementById(`detail_btn_${spot.id}`);
          if (detailBtn) {
            detailBtn.addEventListener('click', () => {
              showSpotDetail(spot);
            });
          }
          
          const navBtn = document.getElementById(`nav_btn_${spot.id}`);
          if (navBtn) {
            navBtn.addEventListener('click', () => {
              handleNavigation(spot);
            });
          }
        }, 100);
      });
    });
  } catch (e) {
    console.warn("添加景点标记失败:", e);
  }
};

const showSpotDetail = (spot) => {
  selectedSpotId.value = spot.id;
  spotDetailVisible.value = true;
  
  if (map) {
    map.setCenter(spot.position);
    map.setZoom(16);
  }
};

const handleNavigation = (spot) => {
  if (!spot || !spot.position) return;
  window.location.href = `https://uri.amap.com/navigation?to=${spot.position[0]},${spot.position[1]},${spot.name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`;
};

const showSearchDialog = () => {
  searchDialogVisible.value = true;
  searchQuery.value = "";
  searchResults.value = [];
};

const handleSearch = () => {
  if (!searchQuery.value) return;
  searchResults.value = spotStore.searchSpots(searchQuery.value);
};

const handleSelectSearchResult = (spot) => {
  searchDialogVisible.value = false;
  showSpotDetail(spot);
};

const toggleDarkMode = () => {
  document.documentElement.classList.toggle("dark");
  isDarkMode.value = !isDarkMode.value;
  
  if (map) {
    map.setMapStyle(
      isDarkMode.value ? "amap://styles/dark" : "amap://styles/normal"
    );
  }
};

const locateUser = () => {
  try {
    if (!map) return;
    
    // 修复定位方法，直接使用控件实例而非getComponent
    const geolocations = map.getControls();
    let geolocation = null;
    
    // 查找定位控件实例
    for (let i = 0; i < geolocations.length; i++) {
      if (geolocations[i] instanceof AMap.Geolocation) {
        geolocation = geolocations[i];
        break;
      }
    }
    
    if (geolocation) {
      geolocation.getCurrentPosition((status, result) => {
        if (status === "complete") {
          const position = result.position;
          map.setCenter(position);
          map.setZoom(15);
          
          new AMap.Marker({
            position,
            map: map,
            icon: new AMap.Icon({
              size: new AMap.Size(25, 34),
              imageSize: new AMap.Size(25, 34),
              image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_g.png",
            }),
          });
          
          ElMessage.success("定位成功");
        } else {
          ElMessage.error("定位失败");
        }
      });
    } else {
      // 如果找不到控件实例，使用API直接定位
      AMap.plugin('AMap.Geolocation', () => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true
        });
        
        geolocation.getCurrentPosition((status, result) => {
          if (status === "complete") {
            const position = result.position;
            map.setCenter(position);
            map.setZoom(15);
            
            new AMap.Marker({
              position,
              map: map,
              icon: new AMap.Icon({
                size: new AMap.Size(25, 34),
                imageSize: new AMap.Size(25, 34),
                image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_g.png",
              }),
            });
            
            ElMessage.success("定位成功");
          } else {
            ElMessage.error("定位失败");
          }
        });
      });
    }
  } catch (e) {
    console.error("定位出错:", e);
    ElMessage.error("定位功能出错");
  }
};

const toggleRuler = () => {
  if (!window.ruler) return;
  
  if (isRulerActive.value) {
    window.ruler.turnOff();
  } else {
    window.ruler.turnOn();
  }
  isRulerActive.value = !isRulerActive.value;
};

const toggleTraffic = () => {
  try {
    // 如果尚未加载Traffic插件，先加载插件
    if (!window.AMap.Traffic) {
      // 显示加载提示
      ElMessage.info("正在加载路况图层...");
      
      // 异步加载Traffic插件
      AMap.plugin(['AMap.Traffic'], () => {
        if (!window.trafficLayer) {
          // 创建Traffic实例
          window.trafficLayer = new AMap.Traffic({
            zIndex: 10
          });
        }
        
        // 显示或隐藏路况图层
        if (showTraffic.value) {
          window.trafficLayer.setMap(null);
        } else {
          window.trafficLayer.setMap(map);
        }
        
        // 切换显示状态
        showTraffic.value = !showTraffic.value;
      });
      return;
    }
    
    // 如果Traffic插件已加载但实例未创建
    if (!window.trafficLayer && window.AMap.Traffic) {
      window.trafficLayer = new AMap.Traffic({
        zIndex: 10
      });
    }
    
    // 如果已有实例，直接切换显示/隐藏
    if (window.trafficLayer) {
      if (showTraffic.value) {
        window.trafficLayer.setMap(null);
      } else {
        window.trafficLayer.setMap(map);
      }
      showTraffic.value = !showTraffic.value;
    }
  } catch (e) {
    console.error("切换路况图层失败:", e);
    ElMessage.error("路况功能暂不可用");
  }
};

const zoomIn = () => map?.zoomIn();
const zoomOut = () => map?.zoomOut();

const resetMapView = () => {
  if (!map) return;
  
  map.setCenter([109.613196, 23.103333]);
  map.setZoom(13);
  map.setPitch(30);
};

watch(isDarkMode, (newValue) => {
  if (map) {
    map.setMapStyle(
      newValue ? "amap://styles/dark" : "amap://styles/normal"
    );
  }
});

// 切换景点展开/折叠
const toggleSpot = (spotId) => {
  const index = expandedSpots.value.indexOf(spotId);
  if (index === -1) {
    expandedSpots.value.push(spotId);
  } else {
    expandedSpots.value.splice(index, 1);
  }
};

// 筛选景点列表
const filteredSpots = computed(() => {
  let spots = spotStore.spots;

  // 应用搜索过滤
  if (spotSearchQuery.value) {
    const query = spotSearchQuery.value.toLowerCase();
    spots = spots.filter(
      (spot) =>
        spot.name.toLowerCase().includes(query) ||
        spot.description.toLowerCase().includes(query),
    );
  }

  // 应用类型过滤
  if (spotFilter.value === "popular") {
    spots = spots.filter((spot) => spot.isPopular);
  } else if (spotFilter.value === "recommended") {
    spots = spots.filter((spot) => spot.isRecommended);
  }

  return spots;
});

// 清理地图资源
const cleanupMap = () => {
  try {
    // 停止测距工具
    if (window.ruler) {
      if (isRulerActive.value) {
        window.ruler.turnOff();
      }
      window.ruler = null;
    }

    // 清理交通图层
    if (window.trafficLayer) {
      window.trafficLayer.setMap(null);
      window.trafficLayer = null;
    }

    // 清理地图搜索服务
    if (window.placeSearch) {
      window.placeSearch = null;
    }

    // 清理全局函数
    if (window.showSpotDetail) window.showSpotDetail = null;
    if (window.handleNavigation) window.handleNavigation = null;

    // 销毁地图实例
    if (map) {
      map.clearMap();
      map.destroy();
      map = null;
    }
    
    mapLoaded.value = false;
  } catch (error) {
    console.warn("清理地图资源时发生错误:", error);
  }
};

onMounted(async () => {
  try {
    // 不再显示控制台日志
    // console.log("组件挂载，准备初始化地图");
    
    // 确保在任何地图操作前设置安全配置
    if (typeof window !== 'undefined') {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
      // 不再显示控制台日志
      // console.log("已设置高德地图安全配置");
    }
    
    // 确保DOM已更新
    await nextTick();
    
    // 延迟初始化，确保DOM完全渲染
    setTimeout(() => {
      initMap();
    }, 800);
    
    // 修复全局函数，正确关联事件处理
    window.showSpotDetail = (spotId) => {
      const spot = spotStore.spots.find(s => s.id === spotId);
      if (spot) showSpotDetail(spot);
    };
    
    window.handleNavigation = (position, name) => {
      if (Array.isArray(position)) {
        window.location.href = `https://uri.amap.com/navigation?to=${position[0]},${position[1]},${name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`;
      }
    };
    
  } catch (error) {
    // 静默处理错误
  }
});

// 组件卸载前清理资源
onBeforeUnmount(() => {
  cleanupMap();
});
</script>

<style lang="scss" scoped>
.map-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-header {
  flex: none;
}

.map-content-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.main-map {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

.map-toolbar {
  position: fixed;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 100;
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 40px;

  :deep(.el-button) {
    width: 40px !important;
    height: 40px !important;
    min-height: 40px !important;
    padding: 0 !important;
    margin: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: flex-start !important;
    border: none !important;

    .el-icon {
      width: 40px !important;
      height: 40px !important;
      font-size: 22px !important;
      margin: 0 !important;
      padding: 0 !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
    }

    &:hover {
      background-color: #f5f7fa !important;
    }

    &.is-active,
    &.el-button--primary {
      background-color: var(--el-color-primary) !important;
      .el-icon {
        color: white !important;
      }
    }
  }

  :deep(.el-divider--horizontal) {
    margin: 4px 0;
    width: 100%;
  }
}

.map-legend {
  position: fixed;
  left: 20px;
  bottom: 20px;
  z-index: 100;
  padding: 12px;
  min-width: 120px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .legend-color {
      width: 16px;
      height: 16px;
      border-radius: 50%;
    }

    .legend-text {
      font-size: 14px;
      color: #666;
    }
  }
}

.dark {
  .map-toolbar,
  .map-legend {
    background-color: #1f2937;
    border: 1px solid #374151;
  }

  .map-toolbar {
    :deep(.el-button) {
      &:hover {
        background-color: #374151 !important;
      }
    }
  }
}

.search-result-item {
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #e5e7eb;
  transition: all 0.2s;

  &:hover {
    background-color: #f3f4f6;
  }

  &:last-child {
    border-bottom: none;
  }
}

.spot-detail {
  .info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    background-color: #f3f4f6;
    border-radius: 6px;

    .el-icon {
      color: #666;
    }
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
  }

  .el-dialog__body {
    padding: 20px;
  }
}

.dark {
  :deep(.el-dialog) {
    background-color: #1f2937;

    .el-dialog__header {
      border-color: #374151;
    }

    .el-dialog__title {
      color: #e5e7eb;
    }
  }

  .search-result-item {
    border-color: #374151;

    &:hover {
      background-color: #374151;
    }
  }

  .spot-detail {
    .info-item {
      background-color: #374151;

      .el-icon {
        color: #9ca3af;
      }
    }
  }
}

.spots-sidebar {
  position: absolute;
  top: 0;
  right: 0;
  width: 320px;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e5e7eb;

  .spots-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }

  .spot-item {
    @apply bg-white dark:bg-gray-800 rounded-lg overflow-hidden mb-3 border border-gray-200 
           dark:border-gray-700 transition-all duration-300;

    .spot-header {
      @apply p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700;
    }

    .spot-content {
      @apply border-t border-gray-200 dark:border-gray-700;

      .spot-image {
        @apply w-full h-48 object-cover;
      }

      .spot-info {
        @apply p-3;

        .spot-desc {
          @apply text-sm text-gray-600 dark:text-gray-400 mb-3;
        }

        .spot-actions {
          @apply flex gap-2 justify-end;
        }
      }
    }

    &.active {
      @apply border-primary-500 dark:border-primary-500;
    }
  }
}

.dark {
  .spots-sidebar {
    background: #1f2937;
    border-color: #374151;

    .spot-item {
      background: #1f2937;
      border-color: #374151;

      .spot-info {
        .spot-name {
          color: #e5e7eb;
        }

        .spot-desc {
          color: #9ca3af;
        }

        .spot-meta {
          .distance {
            color: #9ca3af;
          }
        }
      }
    }
  }
}
</style>
